<?php

/*
 * Table\MotifTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Motif;

class MotifTable extends AbstractTableGateway {

    protected $table = "rh_motif_depart";

    /**
     * Constructeur
     *
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Motif());
	$this->initialize();
    }

    /**
     * Tous les motifs
     *
     * @return ResultSet
     */
    public function getAll() {
	return $this->select();
    }

    /**
     * Tous les motifs en liste
     *
     * @return array
     */
    public function getList() {
	$rows = $this->select(function(\Zend\Db\Sql\Select $select) {
		    $select->order('id DESC');
		});
	$motifs = array();
	// Parcours de la liste
	foreach ($rows as $m) {
	    $motifs[$m->id] = $m->libelle;
	}

	return $motifs;
    }

    /**
     * Récupérer un motif
     *
     * @param int $id
     * @return Motif
     * @throws \Exception
     */
    public function get($id) {
	$row = $this->select(array('id' => $id))->current();
	if (!$row) {
	    throw new \Exception("Impossible de trouver #$id");
	}

	return $row;
    }

    /**
     * Sauvegarder un Motif
     * 
     * @param \RHX\Model\Object\Motif $motif
     * @return int
     */
    public function save(Motif $motif) {
	$data	 = array(
	    'libelle'	 => $motif->libelle,
	    'commentaire'	 => $motif->commentaire,
	);
	$id	 = (int) $motif->id;
	if ($id == 0) {
	    $this->insert($data);

	    return $this->getLastInsertValue();
	}
	else {
	    $this->update($data, $id);

	    return $id;
	}
    }

    /**
     * Effacer un motif
     * 
     * @param int $id
     * @return int
     */
    public function erase($id) {
	return $this->delete(array('id' => $id));
    }

}

?>
